/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ronsicecream.pos.stock.item;

/**
 *
 * @author dedy
 */
import com.buanalintas.bynga.Action;
import com.buanalintas.bynga.Bynga;
import com.buanalintas.bynga.Dictionary;
import com.buanalintas.bynga.Field;
import com.buanalintas.bynga.Logger;
import com.buanalintas.bynga.Page;
import com.buanalintas.bynga.Persistence;
import com.buanalintas.bynga.Template;
import com.buanalintas.bynga.Utility;
import com.buanalintas.bynga.formatter.DateFormatter;
import com.buanalintas.bynga.formatter.NumberFormatter;
import com.buanalintas.bynga.generator.PageList;
import com.ronsicecream.pos.entities.PosMasterItemStock;
import com.ronsicecream.pos.entities.PosMasterType;
import java.util.List;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanArrayDataSource;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;

public class ItemStock extends Page {

    private Field itemStockItemId;
    private Field itemStockValue;
    private Action actionShow = new Action("show", "Show item stock");
    private Action actionExport = new Action("export", "Export item stock");
    private static String MESSAGE_UNIT = "<!--MESSAGE-UNIT-->";
    private static String MESSAGE_STATUS = "<!--MESSAGE-STATUS-->";
    private static String SELECT_UNIT_VALUES = "<!--SELECT-UNIT-VALUES-->";
    private static String SELECT_STATUS_VALUES = "<!--SELECT-STATUS-VALUES-->";
    private static String RECAP_EXPORT = "RECAP-EXPORT";
    private static String RECAP_EXPORT_LINK = "<!--RECAP-EXPORT-LINK-->";
    private static String RECAP_EXPORT_IMAGE = "<!--RECAP-EXPORT-IMAGE-->";
    private static String RECORD = "<!--RECORD-->";
    private static String LIST_DATA = "<!--LIST-DATA-->";
    private static String BUTTON_SEARCH = "<!--BUTTON-SEARCH-->";
    private static String MESSAGE_DAILY = "<!--MESSAGE-DAILY-->";
    private static String MESSAGE_WEEKLY = "<!--MESSAGE-WEEKLY-->";
    private static String MESSAGE_MONTHLY_YEAR = "<!--MESSAGE-MONTHLY-YEAR-->";
    private static String MESSAGE_MONTHLY_MONTH = "<!--MESSAGE-MONTHLY-MONTH-->";
    private static String MESSAGE_YEARLY = "<!--MESSAGE-YEARLY-->";
    private static String MESSAGE_CUSTOM = "<!--MESSAGE-CUSTOM-->";
    private static String SELECT_MODE = "<!--SELECT-MODE-->";
    private static String SELECT_MODE_ONCHANGE = "<!--SELECT-MODE-ONCHANGE-->";
    private static String SELECT_VALUES = "<!--SELECT-VALUES-->";
    private static String SELECT_STATUS = "<!--SELECT-STATUS-->";
    private static String SELECT_UNIT = "<!--SELECT-UNIT-->";
    private static String MODE_DAILY = "MODE-DAILY";
    private static String DAILY_SELECT_DATE = "<!--DAILY-SELECT-DATE-->";
    private static String DAILY_DATE_VALUE = "<!--DAILY-DATE-VALUE-->";
    private static String MODE_WEEKLY = "MODE-WEEKLY";
    private static String WEEKLY_START_DATE_VALUE = "<!--WEEKLY-START-DATE-VALUE-->";
    private static String WEEKLY_SELECT_START_DATE = "<!--WEEKLY-SELECT-START-DATE-->";
    private static String MODE_MONTHLY = "MODE-MONTHLY";
    private static String MONTHLY_SELECT_YEAR = "<!--MONTHLY-SELECT-YEAR-->";
    private static String MONTHLY_SELECT_YEAR_VALUES = "<!--MONTHLY-SELECT-YEAR-VALUES-->";
    private static String MONTHLY_SELECT_MONTH = "<!--MONTHLY-SELECT-MONTH-->";
    private static String MONTHLY_SELECT_MONTH_VALUES = "<!--MONTHLY-SELECT-MONTH-VALUES-->";
    private static String MODE_YEARLY = "MODE-YEARLY";
    private static String YEARLY_SELECT_YEAR = "<!--YEARLY-SELECT-YEAR-->";
    private static String YEARLY_SELECT_YEAR_VALUES = "<!--YEARLY-SELECT-YEAR-VALUES-->";
    private static String MODE_CUSTOM = "MODE-CUSTOM";
    private static String CUSTOM_SELECT_START_DATE = "<!--CUSTOM-SELECT-START-DATE-->";
    private static String CUSTOM_START_DATE_VALUE = "<!--CUSTOM-START-DATE-VALUE-->";
    private static String CUSTOM_SELECT_END_DATE = "<!--CUSTOM-SELECT-END-DATE-->";
    private static String CUSTOM_END_DATE_VALUE = "<!--CUSTOM-END-DATE-VALUE-->";
    private static String WARNING = "<!--WARNING-->";
    private static String TOTAL = "TOTAL";
    private static String TOTAL_CAPTION = "<!--TOTAL-CAPTION-->";
    private static String TOTAL_TEXT = "<!--TOTAL-TEXT-->";
    private NumberFormatter stockFormatter;

    public ItemStock() {
        setTheClass(PosMasterItemStock.class);

        itemStockItemId = new Field();
        itemStockItemId.setName("itemStockItemId");
        itemStockItemId.setCaption("item");
        itemStockItemId.setListProperties(" align=\"left\" size=\"95%\"");
        itemStockItemId.setInputProperties("");
        getFields().add(itemStockItemId);

        itemStockValue = new Field();
        itemStockValue.setName("itemStockValue");
        itemStockValue.setCaption("stock");
        itemStockValue.setListProperties(" align=\"right\" size=\"5%\"");
        itemStockValue.setInputProperties(" ");
        getFields().add(itemStockValue);

        fillFields();

        getActions().add(actionShow);
        getActions().add(actionExport);

//        setExportList(getClass().getResourceAsStream("MasterStockList.jasper"));
        setExport(getClass().getResourceAsStream("ItemStock.jasper"));
    }
    
    @Override
    public void beforeList() {
        if (!getCurrentUnit().getUnitId().equals(1)) {
            getController().setCondition("t.itemStockUnitId.unitId=" + getCurrentUnit().getUnitId());
        }
    }

    @Override
    public void afterInit(HttpServletRequest req, HttpServletResponse res) {
        itemStockItemId.setFormater(DateFormatter.getInstanceDate(this));
        stockFormatter = NumberFormatter.getInstance();
    }

    @Override
    public boolean isSearchVisible() {
        return false;
    }

    @Override
    public boolean isTitleVisible() {
        return false;
    }

    @Override
    public StringBuffer process() {

        if (getAction().equals(actionExport)) {
            try {
                updateExportParams();
                if ("2".equals(getCurrentUser().getUserExport())) {
                    getResponse().setHeader("Content-Type", "application/vnd.ms-excel ");
                } else {
                    getResponse().setHeader("Content-Type", "application/pdf");
                }
                JRDataSource datasource = null;

                String mode = getRequest().getParameter("mode");
                EntityManager em = getController().getEntityManager();
//                String status = getRequest().getParameter("status");

                PosMasterType status = null;

                String filterStatus = Utility.getParameterEmpty(getRequest(), "status");
                System.out.println("filterStatus-->" + filterStatus);
                try {
                    status = (PosMasterType) getEntityManager().createQuery("SELECT t FROM PosMasterType t WHERE t.typeId='" + filterStatus + "' ").setHint(Persistence.REFRESH_HINT, true).getSingleResult();
                    getExportParams().put("status", Utility.getParameterEmpty(getRequest(), "status") + " - " + status.getTypeName());
                } catch (Exception e) {
                    getExportParams().put("status", Utility.getParameterEmpty(getRequest(), "status"));
                }


                getExportParams().put("title", Dictionary.getValue(this, "Report Item Stock"));
                getExportParams().put("filter", Dictionary.getValue(this, "Date") + " " + Utility.getPostParameterEmpty(this, "recapDate"));
                if ("*".equals(Utility.getParameterEmpty(getRequest(), "status"))) {
                    getController().setWhere("");

                } else {
                    getController().setWhere("t.itemStockItemId.itemTypeId.typeName='" + filterStatus + "'");

                }

                getController().setPaginationFilter("&status=" + filterStatus);

                datasource = new JRBeanArrayDataSource(getController().getData(true).toArray());
                JasperPrint jasperPrint = JasperFillManager.fillReport(getClass().getResourceAsStream("ItemStock.jasper"), getExportParams(), datasource);
                if ("2".equals(getCurrentUser().getUserExport())) {
                    JRXlsExporter excelExporter = new JRXlsExporter();
                    excelExporter.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint);
                    excelExporter.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, getResponse().getOutputStream());
                    excelExporter.exportReport();
                } else {
                    JasperExportManager.exportReportToPdfStream(jasperPrint, getResponse().getOutputStream());
                }
                return null;
            } catch (Exception e) {
                Logger.getInstance().log(e);
            }
            return new StringBuffer();

        } else {
            StringBuffer content = Utility.load(Bynga.BYNGA_PACKAGE_THEME + "content.html");
            Template template = new Template();
            template.loadTemplate(getClass().getResourceAsStream("/com/ronsicecream/pos/stock/item/template.html"));

           
            String statusValue = Utility.getPostParameterEmpty(this, "status");
            template.addValue(SELECT_STATUS, Dictionary.getValue(this, "Select Type"));
            String selectStatus = "<option value=\"*\">" + Dictionary.getValue(this, "All Type") + "</option>";

//            Query queryStatus = em.createQuery("SELECT t FROM PosMasterStatus t ORDER BY t.statusName");
            try {
                List<PosMasterType> status = getEntityManager().createQuery("SELECT t FROM PosMasterType t ORDER BY t.typeName").setHint(Persistence.REFRESH_HINT, true).getResultList();
                for (PosMasterType st : status) {
                    selectStatus += "<option value=\"" + st.getTypeName() + "\"" + (statusValue.equals("" + st.getTypeName()) ? " selected" : "") + ">" + st.getTypeName() + "</option>";
                }
            } catch (Exception e) {
            }

            template.addValue(SELECT_STATUS_VALUES, "" + selectStatus);

           
           

            boolean complete = false;
            if (!complete) {
                StringBuffer export = template.getEmptyElement(RECAP_EXPORT);
                Utility.replaceAll(export, RECAP_EXPORT_LINK, "?m=" + getMenu().getMenuName() + "&a=" + actionExport.getName() + "&status=" + Utility.getParameterEmpty(getRequest(), "status"));
                if ("2".equals(getCurrentUser().getUserExport())) {
                        Utility.replaceAll(export, RECAP_EXPORT_IMAGE, "image=command-excel.png");
                    } else {
                        Utility.replaceAll(export, RECAP_EXPORT_IMAGE, "image=command-pdf.png");
                    }
                template.addElement(RECAP_EXPORT, export);
                DateFormatter dateTimeFormatter = DateFormatter.getInstanceDateTime(this);
                if ("*".equals(Utility.getParameterEmpty(getRequest(), "status"))) {
                    getController().setWhere("");
                    
                } else {
                    getController().setWhere("t.itemStockItemId.itemTypeId.typeName='" + statusValue + "' ");
                   
                }

                getController().setPaginationFilter( "&status=" + statusValue );
                complete = true;
            } else {
                template.addValue(template.getEmptyElement(RECAP_EXPORT).toString(), null);
            }

            template.addValue(BUTTON_SEARCH, Dictionary.getValue(this, "Search"));
            int record = getController().getRecordCount();
            template.addValue(RECORD, Dictionary.getValue(this, "Total all record") + ": " + NumberFormatter.getInstance().format(record));
            if (record > 10000000) {
                template.addValue(WARNING, "return confirm('" + Dictionary.getValue(this, "Records is to big need long time to process, approximately") + " " + NumberFormatter.getInstance().format(record) + " " + Dictionary.getValue(this, "records, are you sure want to continue?") + "');");
            } else {
                template.addValue(WARNING, "");
            }
            if (complete) {
                template.addValue(LIST_DATA, PageList.process(this).toString());
            } else {
                template.addValue(LIST_DATA, "-- " + Dictionary.getValue(this, "Please select parameter") + " --");
            }
            Utility.replaceAll(content, Template.CONTENT_CONTENT, template.process().toString());
            updateContent(content, getMenu(), true);
            return content;
        }
    }

    @Override
    public void beforeExport() {
        getExportParams().put("title", Dictionary.getValue(this, "Master Stock"));
    }

    @Override
    public void beforeExportMulti() {
        beforeExport();
    }
}
